package com.hjms.common.swagger.config;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 何杨谊
 * @description: TODO
 * @date 2022/12/31 13:04
 */
@Slf4j
@Configuration
@EnableOpenApi
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public class SwaggerConfig {
    @Autowired
    private SwaggerProperties properties;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(security())
                .securityContexts(Arrays.asList(securityContexts()));
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact(
                properties.getContact().getName(),
                properties.getContact().getUrl(),
                properties.getContact().getEmail()
        );

        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .termsOfServiceUrl(properties.getServiceUrl())
                .contact(contact)
                .version(properties.getVersion())
                .build();
    }

    private List<SecurityScheme> security() {
        List<SecurityScheme> arrayList = new ArrayList();
        arrayList.add(new ApiKey(properties.getAuthorize(), properties.getAuthorize(), "header"));
        return arrayList;
    }
    private SecurityContext securityContexts() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .build();
    }
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "全局设置登录授权token");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference(properties.getAuthorize(), authorizationScopes));
    }
}
